<template>
  <div class="orders-table-container">
    <!-- 状态筛选标签 -->
    <div class="status-filter">
      <div class="status-filter__title">订单状态筛选：</div>
      <div class="status-filter__tags">
        <div class="status-tag" :class="{ 'status-tag--active': activeStatus === 'all' }"
          @click="handleStatusFilter('all')">
          全部
        </div>
        <div class="status-tag" :class="{ 'status-tag--active': activeStatus === 'completed' }"
          @click="handleStatusFilter('completed')">
          已完成
        </div>
        <div class="status-tag" :class="{ 'status-tag--active': activeStatus === 'processing' }"
          @click="handleStatusFilter('processing')">
          处理中
        </div>
        <div class="status-tag" :class="{ 'status-tag--active': activeStatus === 'pending' }"
          @click="handleStatusFilter('pending')">
          待处理
        </div>
        <div class="status-tag" :class="{ 'status-tag--active': activeStatus === 'cancelled' }"
          @click="handleStatusFilter('cancelled')">
          已取消
        </div>
      </div>
    </div>

    <!-- 表格 -->
    <div class="table-wrapper">
      <table class="orders-table">
        <thead>
          <tr>
            <th @click="handleSort('orderNumber')" class="sortable">
              订单编号
              <i class="fas" :class="getSortIconClass('orderNumber')"></i>
            </th>
            <th @click="handleSort('createdAt')" class="sortable">
              订单日期
              <i class="fas" :class="getSortIconClass('createdAt')"></i>
            </th>
            <th>商品信息</th>
            <th @click="handleSort('totalAmount')" class="sortable">
              订单金额
              <i class="fas" :class="getSortIconClass('totalAmount')"></i>
            </th>
            <th @click="handleSort('commission')" class="sortable">
              佣金
              <i class="fas" :class="getSortIconClass('commission')"></i>
            </th>
            <th>状态</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody v-if="!loading && filteredOrders.length > 0">
          <tr v-for="order in paginatedOrders" :key="order.id" class="order-row">
            <td class="order-number">{{ order.orderNumber }}</td>
            <td class="order-date">{{ formatDate(order.createdAt) }}</td>
            <td class="product-info">
              <div class="product-item" v-for="(item, index) in getDisplayedItems(order.items)" :key="index">
                <div class="product-image">
                  <img :src="item.image" :alt="item.name">
                </div>
                <div class="product-details">
                  <div class="product-name">{{ item.name }}</div>
                  <div class="product-price">
                    <span class="discount-price">¥{{ formatNumber(item.discountPrice) }}</span>
                    <span class="original-price">¥{{ formatNumber(item.price) }}</span>
                    <span class="quantity">x{{ item.quantity }}</span>
                  </div>
                </div>
              </div>
              <div class="more-items" v-if="order.items.length > 2">
                +{{ order.items.length - 2 }}件商品
              </div>
            </td>
            <td class="order-amount">¥{{ formatNumber(order.totalAmount) }}</td>
            <td class="commission">
              <div class="commission-amount">¥{{ formatNumber(order.commission) }}</div>
              <div class="commission-rate">{{ order.commissionRate }}</div>
            </td>
            <td class="order-status">
              <span :class="['status-badge', `status-badge--${order.status}`]">
                {{ getStatusLabel(order.status) }}
              </span>
            </td>
            <td class="order-actions">
              <button class="btn-view-details" @click="handleViewDetails(order)">
                查看详情
              </button>
            </td>
          </tr>
        </tbody>
        <tbody v-else-if="loading">
          <tr>
            <td colspan="7" class="loading-state">
              <div class="loading-spinner">
                <i class="fas fa-spinner fa-spin"></i>
                <span>加载中...</span>
              </div>
            </td>
          </tr>
        </tbody>
        <tbody v-else>
          <tr>
            <td colspan="7" class="empty-state">
              <div v-if="activeStatus !== 'all'">
                没有{{ getStatusLabel(activeStatus) }}的订单
              </div>
              <div v-else>
                暂无订单数据
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination" v-if="!loading && totalPages > 1">
      <button class="pagination__btn pagination__btn--prev" :disabled="currentPage === 1"
        @click="handlePageChange(currentPage - 1)">
        <i class="fas fa-chevron-left"></i>
      </button>

      <div class="pagination__pages">
        <button v-for="page in displayedPages" :key="page" class="pagination__page"
          :class="{ 'pagination__page--active': currentPage === page }" @click="handlePageChange(page)">
          {{ page }}
        </button>
      </div>

      <button class="pagination__btn pagination__btn--next" :disabled="currentPage === totalPages"
        @click="handlePageChange(currentPage + 1)">
        <i class="fas fa-chevron-right"></i>
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, defineProps, defineEmits } from 'vue'

// 定义组件接口
interface Props {
  orders: any[]
  loading?: boolean
  itemsPerPage?: number
}

// 定义事件
interface Emits {
  (e: 'view-details', order: any): void
  (e: 'status-filter', status: string): void
  (e: 'sort', column: string, direction: 'asc' | 'desc'): void
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  itemsPerPage: 10
})

const emit = defineEmits<Emits>()

// 内部状态
const currentPage = ref(1)
const activeStatus = ref('all')
const sortConfig = ref({
  key: 'createdAt',
  direction: 'desc' as 'asc' | 'desc'
})

// 根据状态过滤订单
const filteredOrders = computed(() => {
  let result = [...props.orders]

  // 状态过滤
  if (activeStatus.value !== 'all') {
    result = result.filter(order => order.status === activeStatus.value)
  }

  // 排序
  if (sortConfig.value.key) {
    result.sort((a, b) => {
      let aValue = a[sortConfig.value.key]
      let bValue = b[sortConfig.value.key]

      // 处理日期类型
      if (sortConfig.value.key === 'createdAt') {
        aValue = new Date(aValue).getTime()
        bValue = new Date(bValue).getTime()
      }

      if (sortConfig.value.direction === 'asc') {
        return aValue > bValue ? 1 : -1
      } else {
        return aValue < bValue ? 1 : -1
      }
    })
  }

  return result
})

// 分页相关计算
const totalPages = computed(() => {
  return Math.ceil(filteredOrders.value.length / props.itemsPerPage)
})

const paginatedOrders = computed(() => {
  const startIndex = (currentPage.value - 1) * props.itemsPerPage
  const endIndex = startIndex + props.itemsPerPage
  return filteredOrders.value.slice(startIndex, endIndex)
})

// 计算要显示的页码
const displayedPages = computed(() => {
  if (totalPages.value <= 5) {
    return Array.from({ length: totalPages.value }, (_, i) => i + 1)
  }

  const current = currentPage.value
  const total = totalPages.value

  if (current <= 3) {
    return [1, 2, 3, 4, 5]
  } else if (current >= total - 2) {
    return [total - 4, total - 3, total - 2, total - 1, total]
  } else {
    return [current - 2, current - 1, current, current + 1, current + 2]
  }
})

// 处理排序
const handleSort = (column: string) => {
  if (sortConfig.value.key === column) {
    // 切换排序方向
    sortConfig.value.direction = sortConfig.value.direction === 'asc' ? 'desc' : 'asc'
  } else {
    // 设置新的排序列
    sortConfig.value.key = column
    sortConfig.value.direction = 'desc'
  }

  // 重置到第一页
  currentPage.value = 1

  // 通知父组件
  emit('sort', column, sortConfig.value.direction)
}

// 获取排序图标样式
const getSortIconClass = (column: string) => {
  if (sortConfig.value.key !== column) {
    return 'fa-sort'
  }
  return sortConfig.value.direction === 'asc' ? 'fa-sort-up' : 'fa-sort-down'
}

// 处理状态筛选
const handleStatusFilter = (status: string) => {
  activeStatus.value = status
  currentPage.value = 1 // 重置到第一页
  emit('status-filter', status)
}

// 处理页码变化
const handlePageChange = (page: number) => {
  if (page >= 1 && page <= totalPages.value) {
    currentPage.value = page
  }
}

// 处理查看详情
const handleViewDetails = (order: any) => {
  emit('view-details', order)
}

// 格式化数字
const formatNumber = (num: number) => {
  return num.toFixed(2)
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  switch (status) {
    case 'completed': return '已完成'
    case 'processing': return '处理中'
    case 'pending': return '待处理'
    case 'cancelled': return '已取消'
    default: return '全部'
  }
}

// 获取要显示的商品项
const getDisplayedItems = (items: any[]) => {
  return items.slice(0, 2) // 每个订单最多显示2个商品
}

// 监听props.orders变化，重置分页
watch(() => props.orders, () => {
  currentPage.value = 1
}, { deep: true })
</script>

<style scoped lang="scss">
.orders-table-container {
  margin-bottom: 24px;
}

// 状态筛选标签
.status-filter {
  display: flex;
  align-items: center;
  margin-bottom: 16px;

  &__title {
    font-size: 14px;
    color: #6C757D;
    margin-right: 12px;
    white-space: nowrap;
  }

  &__tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
  }

  .status-tag {
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 13px;
    background-color: #F8F9FA;
    color: #6C757D;
    cursor: pointer;
    transition: all 0.2s;

    &:hover {
      background-color: #E9ECEF;
    }

    &--active {
      background-color: #28A745;
      color: #fff;

      &:hover {
        background-color: darken(#28A745, 5%);
      }

      &.status-tag[status="completed"] {
        background-color: #28A745; // 绿色 - 已完成
      }

      &.status-tag[status="processing"] {
        background-color: #007BFF; // 蓝色 - 处理中
      }

      &.status-tag[status="pending"] {
        background-color: #FFC107; // 黄色 - 待处理
      }

      &.status-tag[status="cancelled"] {
        background-color: #DC3545; // 红色 - 已取消
      }
    }
  }
}

// 表格样式
.table-wrapper {
  overflow-x: auto;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.orders-table {
  width: 100%;
  border-collapse: collapse;
  background-color: #fff;

  th,
  td {
    padding: 12px 16px;
    text-align: left;
    border-bottom: 1px solid #E9ECEF;
  }

  th {
    background-color: #F8F9FA;
    font-size: 14px;
    font-weight: 600;
    color: #2F3542;
    white-space: nowrap;

    &.sortable {
      cursor: pointer;
      transition: background-color 0.2s;

      &:hover {
        background-color: #E9ECEF;
      }

      i {
        margin-left: 4px;
        font-size: 12px;
        color: #ADB5BD;
      }
    }
  }

  // 行悬停效果
  tbody .order-row {
    transition: background-color 0.2s;

    &:hover {
      background-color: #F8F9FA;
    }
  }

  // 单元格样式
  .order-number {
    font-family: monospace;
    font-size: 14px;
    color: #2F3542;
  }

  .order-date {
    white-space: nowrap;
    font-size: 14px;
    color: #6C757D;
  }

  .product-info {
    .product-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      &:last-child {
        margin-bottom: 0;
      }

      .product-image {
        width: 40px;
        height: 40px;
        border-radius: 4px;
        overflow: hidden;
        margin-right: 12px;

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .product-details {
        flex: 1;

        .product-name {
          font-size: 14px;
          color: #2F3542;
          margin-bottom: 4px;
        }

        .product-price {
          display: flex;
          align-items: center;
          font-size: 13px;

          .discount-price {
            color: #FF4757;
            font-weight: 500;
            margin-right: 6px;
          }

          .original-price {
            color: #ADB5BD;
            text-decoration: line-through;
            margin-right: 6px;
          }

          .quantity {
            color: #6C757D;
          }
        }
      }
    }

    .more-items {
      margin-top: 8px;
      font-size: 13px;
      color: #6C757D;
    }
  }

  .order-amount {
    font-size: 16px;
    font-weight: 600;
    color: #2F3542;
  }

  .commission {
    .commission-amount {
      font-size: 15px;
      font-weight: 600;
      color: #28A745;
      margin-bottom: 2px;
    }

    .commission-rate {
      font-size: 12px;
      color: #6C757D;
    }
  }

  .order-status {
    .status-badge {
      display: inline-block;
      padding: 4px 8px;
      border-radius: 4px;
      font-size: 12px;
      font-weight: 500;

      &--completed {
        background-color: #e8f7ef;
        color: #28A745;
      }

      &--processing {
        background-color: #e8f2ff;
        color: #007BFF;
      }

      &--pending {
        background-color: #fff8e6;
        color: #FFC107;
      }

      &--cancelled {
        background-color: #ffe8e8;
        color: #DC3545;
      }
    }
  }

  .order-actions {
    .btn-view-details {
      padding: 6px 12px;
      background-color: #F8F9FA;
      border: 1px solid #DFE3E8;
      border-radius: 4px;
      font-size: 13px;
      color: #2F3542;
      cursor: pointer;
      transition: all 0.2s;

      &:hover {
        background-color: #E9ECEF;
      }
    }
  }

  // 加载状态
  .loading-state {
    padding: 32px;
    text-align: center;

    .loading-spinner {
      display: flex;
      flex-direction: column;
      align-items: center;
      color: #6C757D;

      i {
        font-size: 24px;
        margin-bottom: 8px;
        color: #FF4757;
      }
    }
  }

  // 空状态
  .empty-state {
    padding: 32px;
    text-align: center;
    color: #6C757D;
    font-size: 14px;
  }
}

// 分页控件
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24px;

  &__btn {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #F8F9FA;
    border: 1px solid #DFE3E8;
    border-radius: 4px;
    color: #2F3542;
    cursor: pointer;
    transition: all 0.2s;

    &:hover:not(:disabled) {
      background-color: #E9ECEF;
    }

    &:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    &--prev {
      margin-right: 8px;
    }

    &--next {
      margin-left: 8px;
    }
  }

  &__pages {
    display: flex;
    gap: 4px;
  }

  &__page {
    width: 32px;
    height: 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #F8F9FA;
    border: 1px solid #DFE3E8;
    border-radius: 4px;
    color: #2F3542;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;

    &:hover:not(&--active) {
      background-color: #E9ECEF;
    }

    &--active {
      background-color: #FF4757;
      border-color: #FF4757;
      color: #fff;
    }
  }
}

// 响应式调整
@media (max-width: 768px) {
  .status-filter {
    flex-direction: column;
    align-items: flex-start;

    &__title {
      margin-bottom: 8px;
    }

    &__tags {
      width: 100%;
    }
  }
}
</style>
